<template>
  <div class="upload-container">
    <h2>Excel文件上传</h2>
    <div class="upload-box">
      <input
        type="file"
        ref="fileInput"
        @change="handleFileChange"
        accept=".xlsx,.xls"
        style="display: none"
      />
      <button class="upload-btn" @click="triggerFileInput">选择文件</button>
      <span v-if="selectedFile" class="file-name">{{ selectedFile.name }}</span>
    </div>
    <button 
      v-if="selectedFile" 
      class="submit-btn" 
      @click="uploadFile"
      :disabled="uploading"
    >
      {{ uploading ? '上传中...' : '上传文件' }}
    </button>

    <div v-if="uploadResult" class="result-container">
      <h3>上传结果：</h3>
      <pre>{{ JSON.stringify(uploadResult, null, 2) }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import request from '../utils/request'
import { API_ENDPOINTS } from '../config/api'
import { useRouter } from 'vue-router'

const router = useRouter()
const fileInput = ref(null)
const selectedFile = ref(null)
const uploading = ref(false)
const uploadResult = ref(null)

const triggerFileInput = () => {
  fileInput.value.click()
}

const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    selectedFile.value = file
    uploadResult.value = null
  }
}

const uploadFile = async () => {
  if (!selectedFile.value) {
    alert('请选择文件')
    return
  }

  const formData = new FormData()
  formData.append('file', selectedFile.value)

  try {
    uploading.value = true
    const response = await request.post(API_ENDPOINTS.upload, formData)

    alert('上传成功！')
    setTimeout(() => {
      router.push('/tasks')
    }, 1000)
  } catch (error) {
    alert(error.response?.data?.error || '上传失败')
  } finally {
    uploading.value = false
    selectedFile.value = null
    fileInput.value.value = ''
  }
}
</script>

<style scoped>
.upload-container {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.upload-box {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 20px 0;
}

.upload-btn, .submit-btn {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-btn:hover, .submit-btn:hover {
  background-color: #45a049;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.file-name {
  color: #666;
}

.result-container {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>